package console

import (
	"WIKIHepler_PCR/database"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"time"
)

//快速导出可用数据 event.json
func Do_get_output() {
	time1 := time.Now().AddDate(0, 0, -3)

	objs := database.EVENT_GetNewest(time1.Unix())

	var ejson [][]interface{}

	for _, obj := range objs {
		ejson = append(ejson, obj.FORMAT_WIKI())
	}
	jsonstr, _ := json.Marshal(ejson)

	file, err := os.OpenFile("./event.json", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0777)
	if err != nil {
		fmt.Println(err.Error())
	}
	file.Write([]byte(string(jsonstr)))
	file.Close()

}

//导出数据
func Export_event() error {
	objs, err := database.EVENT_GetAll()
	if err != nil {
		return err
	}
	if len(objs) == 0 {
		return errors.New("空数据")
	}

	jsonstr, _ := json.Marshal(objs)
	file, err := os.OpenFile("./eventdata.json", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0777)
	if err != nil {
		return err
	}
	file.Write([]byte(string(jsonstr)))
	file.Close()
	return nil
}

//导入数据
func Import_event() (err error) {
	file, err := os.OpenFile("./eventdata.json", os.O_RDONLY, 0777)
	if err != nil {
		return
	}
	defer file.Close()
	f, _ := ioutil.ReadAll(file)
	var objs []database.EVENT
	err = json.Unmarshal(f, &objs)
	if err != nil {
		return
	}
	for _, v := range objs {
		database.EVENT_Update(v)
	}
	return nil
}

//获取模板信息
func Tplte_Get() (data []Tplte) {
	file, err := os.OpenFile("./event_template.json", os.O_RDONLY, 0777)
	if err != nil {
		return
	}
	defer file.Close()
	f, _ := ioutil.ReadAll(file)
	err = json.Unmarshal(f, &data)
	if err != nil {
		return
	}
	return
}
